package com.persondemo.videoappliction.ui.dianping;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.DyReleaseEntity;
import com.persondemo.videoappliction.bean.UpPingCeBean;
import com.persondemo.videoappliction.bean.UpimgBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.photo.PhotoPickerActivity;
import com.persondemo.videoappliction.photo.utils.ImageLoader;
import com.persondemo.videoappliction.photo.utils.OtherUtils;
import com.persondemo.videoappliction.ui.base.AppManager;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.dianping.contract.PingLunContract;
import com.persondemo.videoappliction.ui.dianping.presenter.PinglunPresenter;
import com.persondemo.videoappliction.utils.PreferenceUtil;
import com.persondemo.videoappliction.utils.T;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PutDianPingActivity extends BaseActivity<PinglunPresenter> implements PingLunContract.View {
    @BindView(R.id.putdianping_back)
    ImageView putdianpingBack;
    @BindView(R.id.putdianping_text)
    TextView putdianpingText;
    @BindView(R.id.cccc)
    TextView cccc;
    @BindView(R.id.put_Ratingbar)
    RatingBar putRatingbar;
    @BindView(R.id.putdianping_edit)
    EditText putdianpingEdit;
    @BindView(R.id.releaseGridView)
    GridView releaseGridView;
    @BindView(R.id.addImg)
    ImageView addImg;
    @BindView(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    private int mColumnWidth;
    private GridAdapter mAdapter;
    private GridAdapter gridAdapter;
    private List<DyReleaseEntity> dyReleaseEntityList = new ArrayList<>();
    private List<String> mResults = new ArrayList<>();
    private String img = "";
    private String imei = "", id = "";

    @Override
    public void onRetry() {

    }

    @Override
    public int getContentLayout() {
        return R.layout.module_activity_putdianping;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }


    @Override
    public void bindView(View view, Bundle savedInstanceState) {
        putdianpingBack.setOnClickListener(v -> AppManager.getAppManager().finishActivity());
        putdianpingEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @SuppressLint("ResourceAsColor")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() > 0) {
                    putdianpingText.setTextColor(Color.parseColor("#ff9829"));
                }else {
                    putdianpingText.setTextColor(Color.parseColor("#b4b4b4"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    private void gopinlun(String id) {
        Intent intent = new Intent(PutDianPingActivity.this, PinglunActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void updata() {
        String ratnum = putRatingbar.getRating() + "";
        String content = putdianpingEdit.getText().toString().trim();
        if (TextUtils.isEmpty(PreferenceUtil.getString("imei", ""))) {
            imei = "";
        } else {
            imei = PreferenceUtil.getString("imei", "");
        }
        if (mPresenter != null) {
            mPresenter.uppingce(id, content, imei, img, ratnum);
        }
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            id = intent.getStringExtra("id");
            Log.i("id", "id=" + id);
        }
        int screenWidth = OtherUtils.getWidthInPx(getApplicationContext());
        mColumnWidth = (screenWidth - OtherUtils.dip2px(getApplicationContext(), 4)) / 3;
        dyReleaseEntityList.clear();
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("1");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        gridAdapter = new GridAdapter(dyReleaseEntityList);
        releaseGridView.setAdapter(gridAdapter);
        gridAdapter.notifyDataSetChanged();
        putdianpingEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    T.showShort(PutDianPingActivity.this, "最多输入100字！");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                showResult(result);
            }
        }
    }

    private void showResult(ArrayList<String> paths) {
        mResults.clear();
        dyReleaseEntityList.clear();
        gridAdapter.notifyDataSetChanged();
        for (int i = 0; i < paths.size(); i++) {
            DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
            dyReleaseEntity.setImgPath(paths.get(i));
            dyReleaseEntity.setImgType("1");
            dyReleaseEntityList.add(dyReleaseEntity);
            mResults.add(paths.get(i));
        }
        DyReleaseEntity dyReleaseEntity = new DyReleaseEntity();
        dyReleaseEntity.setImgPath("2");
        dyReleaseEntity.setImgType("2");
        dyReleaseEntityList.add(dyReleaseEntity);
        if (mAdapter == null) {
            mAdapter = new GridAdapter(dyReleaseEntityList);
        }
        releaseGridView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        if (dyReleaseEntityList.size() > 8) {
            dyReleaseEntityList.remove(9);
        }
        yasuo(paths);

    }

    private void yasuo(ArrayList<String> photos) {
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        Log.i("lidaming", "11");
//                    filesList.add(file);
                        if (mPresenter != null) {
                            RequestBody requestFile =
                                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
                            MultipartBody.Part body =
                                    MultipartBody.Part.createFormData("imgs", file.getName(), requestFile);
                            showLoadingDialog("图片上传中。。。");
                            mPresenter.upimgdata(body);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void imgdata(UpimgBean upimgBean) {
        hideLoadingDialog();
        if (upimgBean.getStatus() == 1) {
            if (TextUtils.isEmpty(img)) {
                img = upimgBean.getData();
            } else {
                img = img + "," + upimgBean.getData();
            }
            T.showShort(PutDianPingActivity.this, upimgBean.getMsg());

        } else {
            T.showShort(PutDianPingActivity.this, upimgBean.getMsg() + "请重新上传图片！");
        }
    }

    @Override
    public void loadpingce(UpPingCeBean upPingCeBean) {
         if (upPingCeBean.getStatus()==1){
             T.showShort(PutDianPingActivity.this,upPingCeBean.getMsg());
             gopinlun(id);
         }else {
             T.showShort(PutDianPingActivity.this,upPingCeBean.getMsg());
         }
    }

    @OnClick(R.id.putdianping_text)
    public void onViewClicked() {
        updata();
    }


    public class GridAdapter extends BaseAdapter {
        private List<DyReleaseEntity> pathList;

        public GridAdapter(List<DyReleaseEntity> pathList) {
            this.pathList = pathList;
        }

        @Override
        public int getCount() {
            return pathList.size();
        }

        @Override
        public Object getItem(int position) {
            return pathList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mColumnWidth * 9 / 10, mColumnWidth);
                holder.imageView.setLayoutParams(params);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (pathList.get(position).getImgType().equals("2")) {
                holder.imageView.setBackgroundResource(R.drawable.ic_xiangji);
                holder.imageView.setEnabled(true);
                holder.imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PutDianPingActivity.this, PhotoPickerActivity.class);
                        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
                        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 6);
                        startActivityForResult(intent, 1);
                    }
                });
            } else {
                ImageLoader.getInstance().display(pathList.get(position).getImgPath(), holder.imageView, mColumnWidth, mColumnWidth);
                holder.imageView.setEnabled(false);
            }
            return convertView;
        }

        private class ViewHolder {
            public ImageView imageView;
        }
    }
}
